<template>
  <div>
    <search-form @search="getTableData" @reset="clearSearch">
      <el-col :span="8" :xs="24" v-show="$permiss[1384]">
        <el-form-item :label="$t('所属租户')">
          <el-select style="width: 100%" v-model="page.tenantId" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('收款人姓名')" label-width="100px">
          <el-input style="width: 100%" v-model="page.userName"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('银行账号')">
          <el-input style="width: 100%" v-model="page.bankAcc"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('打款状态')">
          <el-select style="width: 100%" v-model="page.status" clearable>
            <el-option :value="1" :label="$t('打款中')"></el-option>
            <el-option :value="2" :label="$t('打款成功')"></el-option>
            <el-option :value="3" :label="$t('打款失败')"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('代发类型')">
          <el-select style="width: 100%" v-model="page.issuType" clearable>
            <el-option :value="0" :label="$t('单笔')"></el-option>
            <el-option :value="1" :label="$t('批量')"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('操作人')">
          <el-input style="width: 100%" v-model="page.adminUserName"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('交易流水')">
          <el-input style="width: 100%" v-model="page.platformOrderId"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('打款发起时间')" label-width="100px">
          <el-date-picker
              v-model="page.startTimeValue"
              style="width: 100%"
              type="daterange"
              range-separator="~"
              unlink-panels
              value-format="yyyy-MM-dd"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('打款结束时间')" label-width="100px">
          <el-date-picker
              v-model="page.endTimeValue"
              style="width: 100%"
              type="daterange"
              range-separator="~"
              unlink-panels
              value-format="yyyy-MM-dd"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </search-form>
    <el-card shadow="never" style="margin-top: 10px">
      <div style="margin-bottom: 10px;text-align:right">
        <el-button @click="exportsExcel" type="info" icon="el-icon-upload2" :loading="exportsLoading">{{$t('导出')}}</el-button>
        <el-button type="primary" @click="visible = true">{{ $t('代发工资') }}</el-button>
      </div>
      <Table :loading="loading" max-height="600px" :table-data="tableData" :table-column="tableColumn" :page="page"
             @handleCurrentChange="handleCurrentChange"
             @handleSizeChange="handleSizeChange"/>
    </el-card>
    <Dialog :visible.sync="visible" :confirm-loading="confirmLoading" :title="$t('代发工资')" @cancel="visible = false"
            @close="clearForm"
            @confirm="formConfirm">
      <el-form ref="form" :model="form" :rules="rulesForm" label-width="100px">
        <el-form-item :label="$t('代发类型')">
          <el-radio-group v-model="form.issuType">
            <el-radio :label="0">{{ $t('单笔代发') }}</el-radio>
            <el-radio :label="1">{{ $t('批量代发') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('所属租户')" prop="tenantId">
          <el-select style="width: 100%" v-model="form.tenantId">
            <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('打款事由')" prop="paymentReason">
          <el-input style="width: 100%" v-model="form.paymentReason"></el-input>
        </el-form-item>
        <el-form-item v-if="form.issuType === 0" key="1" :label="$t('收款人姓名')" prop="userName">
          <el-input style="width: 100%" v-model="form.userName"></el-input>
        </el-form-item>
        <el-form-item v-if="form.issuType === 0" key="2" :label="$t('手机号码')" prop="userPhone">
          <el-input style="width: 100%" oninput="value = value.replace(/[^\d]/g, '')"
                    v-model="form.userPhone"></el-input>
        </el-form-item>
        <el-form-item v-if="form.issuType === 0" key="3" :label="$t('身份证号码')" prop="idCard">
          <el-input style="width: 100%" oninput="value = value.replace(/[^\d]/g, '')"
                    v-model="form.idCard"></el-input>
        </el-form-item>
        <el-form-item v-if="form.issuType === 0" key="4" :label="$t('银行名称')" prop="bankName">
          <el-input style="width: 100%" v-model="form.bankName"></el-input>
        </el-form-item>
        <el-form-item v-if="form.issuType === 0" key="5" :label="$t('银行账号')" prop="bankAcc">
          <el-input style="width: 100%" v-model="form.bankAcc"></el-input>
        </el-form-item>
        <el-form-item v-if="form.issuType === 0" key="6" :label="$t('打款金额')" prop="payAmount">
          <el-input style="width: 100%" oninput="value = value.replace(/[^\d.]/g, '')"
                    v-model="form.payAmount"></el-input>
        </el-form-item>
        <el-form-item v-if="form.issuType === 0" key="7" :label="$t('备注')">
          <el-input type="textarea" :rows="4" style="width: 100%" v-model="form.remarks"></el-input>
        </el-form-item>
        <el-row v-if="form.issuType === 1" :gutter="24" style="margin:0">
          <div style="margin-left: 100px">
            <el-link type="primary" href="https://ddhkapps.oss-cn-hongkong.aliyuncs.com/Payroll%20in%20bulk.xlsx"
                     size="mini" icon="el-icon-download" style="margin-right:15px">
              {{ $t('下载模板') }}
            </el-link>
            <div style="margin-top: 15px">
              <el-upload
                  action="#"
                  :limit="1"
                  style="display: inline-block"
                  :on-remove="fileRemove"
                  :http-request="requestUpload"
                  :file-list="fileList"
                  accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              >
                <el-button type="primary" size="mini" icon="el-icon-upload2">{{ $t('导入') }}</el-button>
              </el-upload>
            </div>
          </div>

        </el-row>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import {dateFormatSection} from '@/utils/tools'
import {payWagesList, payWagesConfirm,payWagesExport} from '@/api/pay'
import {selectTenant} from "@/api/system";
import XLSX from 'xlsx/dist/xlsx.mini.min'
import {export_json_to_excel} from "@/utils/exportExcel";

export default {
  name: "wagesRepayment",
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      loading: false,
      tenantList: [],
      tableColumn: [
        {label: this.$t('所属租户'), prop: "tenantName", align: "center", isHide: this.$permiss[1384]},
        {label: this.$t('代发类型'), prop: 'issuType', minWidth: 100,},
        {label: this.$t('打款事由'), prop: 'paymentReason', minWidth: 100},
        {label: this.$t('收款人姓名'), prop: 'userName', minWidth: 100},
        {label: this.$t('手机号码'), prop: 'userPhone',},
        {label: this.$t('身份证号码'), prop: 'idCard', minWidth: 100},
        {label: this.$t('银行名称'), prop: 'bankName', minWidth: 100},
        {label: this.$t('银行账号'), prop: 'bankAcc', minWidth: 100},
        {label: this.$t('打款金额'), prop: 'payAmount', minWidth: 100},
        {label: this.$t('交易流水'), prop: 'platformOrderId', minWidth: 100},
        {label: this.$t('打款发起时间'), prop: 'payStartTime', minWidth: 150},
        {label: this.$t('打款结束时间'), prop: 'payEndTime', minWidth: 150},
        {label: this.$t('打款状态'), prop: 'status',},
        {label: this.$t('上次失败原因'), prop: 'respMessage', minWidth: 150},
        {label: this.$t('备注'), prop: 'remarks', minWidth: 100},
        {label: this.$t('操作人'), prop: 'adminUserName',},
      ],
      tableData: [],
      visible: false,
      form: {
        issuType: 0,
        tenantId: null,
        paymentReason: '',
        userName: '',
        userPhone: '',
        idCard: '',
        bankName: '',
        bankAcc: '',
        payAmount: ''
      },
      rulesForm: {
        tenantId: [
          {trigger: 'change', required: true, message: this.$t('请选择'),}
        ],
        paymentReason: [
          {required: true, message: this.$t('不能为空'), trigger: 'blur'}
        ],
        userName: [
          {required: true, message: this.$t('不能为空'), trigger: 'blur'}
        ],
        // userPhone: [
        //   {required: true, message: this.$t('不能为空'), trigger: 'blur'}
        // ],
        // idCard: [
        //   {required: true, message: this.$t('不能为空'), trigger: 'blur'}
        // ],
        bankName: [
          {required: true, message: this.$t('不能为空'), trigger: 'blur'}
        ],
        bankAcc: [
          {required: true, message: this.$t('不能为空'), trigger: 'blur'}
        ],
        payAmount: [
          {required: true, message: this.$t('不能为空'), trigger: 'blur'}
        ]
      },
      fileList: [],
      batchImportList: [],
      confirmLoading: false,
      exportsLoading:false
    }
  },
  mounted() {
    selectTenant().then(res => {
      this.tenantList = res.data
    })
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const [payStartTime, payStartTimeEnd] = dateFormatSection(this.page.startTimeValue)
      const [payEndTime, payEndTimeEnd] = dateFormatSection(this.page.endTimeValue)
      const params = {
        ...this.page,
        payStartTime, payStartTimeEnd,
        payEndTime, payEndTimeEnd
      }
      delete params.startTimeValue
      delete params.endTimeValue
      this.loading = true
      const res = await payWagesList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list.map(item => {
          item.status = item.status === 1 ? this.$t('打款中') : item.status === 2 ? this.$t('打款成功') : this.$t('打款失败')
          item.issuType = item.issuType === 0 ? this.$t('单笔代发') : this.$t('批量代发')
          return item
        })
        this.page.total = total
        this.loading = false
      }
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    },
    formConfirm() {
      this.$refs.form.validate(async v => {
        if (v) {
          let params
          if (this.form.issuType === 0) {
            params = [this.form]
          } else {
            if (this.batchImportList.length === 0) return this.$message.error(this.$t('文件无数据或未导入文件'))
            params = this.batchImportList.map(item => {
              return {
                ...item,
                issuType: this.form.issuType,
                tenantId: this.form.tenantId,
                paymentReason: this.form.paymentReason
              }
            })
          }
          this.confirmLoading = true
          const res = await payWagesConfirm(params)
          if (res.code === 1) {
            this.confirmLoading = false
            this.visible = false
            this.getTableData()
            this.$message.success(this.$t('操作成功'))
          } else {
            this.confirmLoading = false
          }
        }
      })
    },
    requestUpload({file}) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader()
        reader.onload = async (e) => {
          let bstr = e.target.result;
          let wb = XLSX.read(bstr, {type: 'binary', cellDates: true});
          let wsname = wb.SheetNames[0];
          let ws = wb.Sheets[wsname];
          const list = []
          let data = XLSX.utils.sheet_to_json(ws, {header: 1});
          for (let i = 0; i < data.length; i++) {
            if (i !== 0) {
              list.push({
                userName: data[i][0],
                userPhone: data[i][1],
                idCard: data[i][2],
                bankName: data[i][3],
                bankAcc: data[i][4],
                payAmount: data[i][5],
                remarks: data[i][6]
              })
              // 校验每一列的值
              for (let j = 0; j < list.length; j++) {
                for (let key in list[j]) {
                  if (key !== 'remarks' && key !== 'userPhone' && key !== 'idCard') {
                    if (!list[j][key]) {
                      this.$message.error(key + '值校验错误')
                      reject()
                      return
                    }
                  }
                }
              }
            }
          }
          this.$message.success(this.$t('导入成功'))
          this.batchImportList = list
          resolve()
        }
        reader.readAsBinaryString(file);
      })
    },
    fileRemove() {
      this.batchImportList = []
    },
    clearForm() {
      this.batchImportList = []
      this.form = {
        issuType: 0,
        tenantId: null,
        paymentReason: '',
        userName: '',
        userPhone: '',
        idCard: '',
        bankName: '',
        bankAcc: '',
        payAmount: ''
      }
      this.$refs.form.resetFields()
    },
    // 导出excel
    async exportsExcel() {
      this.exportsLoading = true;
      const [payStartTime, payStartTimeEnd] = dateFormatSection(this.page.startTimeValue)
      const [payEndTime, payEndTimeEnd] = dateFormatSection(this.page.endTimeValue)
      const params = {
        ...this.page,
        payStartTime, payStartTimeEnd,
        payEndTime, payEndTimeEnd
      }
      delete params.startTimeValue
      delete params.endTimeValue
      const res = await payWagesExport(params);
      if (res.code === 1) {
        const headerData = [...this.tableColumn].filter(item => {
          const result = res.data.filter(i => {
            //过滤没有权限的字段
            return typeof i[item.prop] !== "undefined"
          })
          return result.length !== 0
        })
        const column = headerData.map(item => item.label)
        const filterVal = headerData.map(item => item.prop)
        const list = [...res.data].map((item) => {
          item.status = item.status === 1 ? this.$t('打款中') : item.status === 2 ? this.$t('打款成功') : this.$t('打款失败')
          item.issuType = item.issuType === 0 ? this.$t('单笔代发') : this.$t('批量代发')
          return item
        }).map((v) => filterVal.map((j) => v[j]));
        const fileName = this.$t("非业务打款");
        export_json_to_excel({
          header: column,
          data: list,
          filename: fileName,
        });
        this.exportsLoading = false;
      } else {
        this.exportsLoading = false;
      }
    },
  }
}
</script>

<style scoped>

</style>
